using CfgTable;
using Cysharp.Threading.Tasks;
using IQIGame.Onigao.Framework;
using System.Collections.Generic;
using UnityEngine;

namespace IQIGame.Onigao.GamePlay
{
    public abstract class TEntityViewController : TModuleController
    {
        /// <summary>
        /// 导致停止移动的表现组件
        /// </summary>
        protected HashSet<EntityUIViewComponent> _stopMoveView = new HashSet<EntityUIViewComponent>();
        /// <summary>
        /// 会有持续性表现的展示，这类表现在开启战斗或其他切换全屏显示时需要关闭
        /// </summary>
        protected HashSet<EntityUIViewComponent> _awaitViewList = new HashSet<EntityUIViewComponent>();

        protected abstract TViewEntity playerAvatarEntity { get; }

        protected override void OnModuleGameplayInit()
        {

        }

        protected override void OnSceneLoaded()
        {

        }

        public void AddStopMoveView(EntityUIViewComponent viewCom)
        {
            _stopMoveView.Add(viewCom);
            MsgDispatcher.Broadcast(MsgEventType.EntityEnterStateBubble);
        }

        public void RemoveStopMoveView(EntityUIViewComponent viewCom)
        {
            _stopMoveView.Remove(viewCom);
            if (_stopMoveView.Count == 0)
            {
                MsgDispatcher.Broadcast(MsgEventType.EntityExitStateBubble);
            }
        }

        public bool AddAwaitView(EntityUIViewComponent viewCom)
        {
            return _awaitViewList.Add(viewCom);
        }

        public bool RemoveAwaitView(EntityUIViewComponent viewCom)
        {
            return _awaitViewList.Remove(viewCom);
        }

        /// <summary>
        /// 开始实体的气泡
        /// </summary>
        /// <param name="view"></param>
        /// <param name="bubbleGroup"></param>
        /// <returns></returns>
        public async UniTaskVoid StartEntityBubble(EntityUIViewComponent view, int bubbleGroupId, List<int> validBubbleIds)
        {
            if (view == null)
            {
                return;
            }
            var bubblueGroupCfg = TableCenter.levelEntityBubbleGroup.Get(bubbleGroupId);
            if (bubblueGroupCfg == null || validBubbleIds.Count <= 0)
            {
                LogGame.LogError("bubble group is null or bubbleId List is null :" + bubbleGroupId);
                return;
            }

            AddAwaitView(view);

            bool needRotate = false;
            Quaternion oldRotation = Quaternion.identity;
            var moveComponent = view.entity.GetComponent<EntityMoveComponent>(ETComponentType.EntityMove);
            if (bubblueGroupCfg.IsItFaceTo) //仅实体气泡有效，玩家气泡无效
            {
                //面向玩家
                var mainCharacter = playerAvatarEntity;
                if (moveComponent != null)
                {
                    oldRotation = view.entity.unityRotationOfData;
                    needRotate = true;
                    if (moveComponent.rotatonNeedRestore)
                    {
                        // 打断上次动画
                        moveComponent.rotatonNeedRestore = false;
                        moveComponent.transform.DOKill();
                        moveComponent.rotatonNeedRestore = true;
                    }
                    else
                    {
                        moveComponent.StartSaveRotation();
                    }
                    await moveComponent.RotateWithAnimation(mainCharacter.unityPosOfData);
                }
            }

            int randIndex = Random.Range(0, validBubbleIds.Count);
            int bid = validBubbleIds[randIndex];
            CfgLevelEntityBubble cfgResult = TableCenter.levelEntityBubble.Get(bid);

            if (cfgResult != null)
            {
                // 关闭移动和交互ui
                if (bubblueGroupCfg.IsItImmovable)
                {
                    AddStopMoveView(view);
                }

                bool result = await view.ShowHeadDialogByBubble(cfgResult.Id);

                if (result)
                {
                    //气泡结束
                    RemoveStopMoveView(view);
                }
            }
            RemoveAwaitView(view);

            if (needRotate) //仅实体气泡有效，玩家气泡无效
            {
                // 恢复旋转
                if (moveComponent != null && moveComponent.rotatonNeedRestore)
                {
                    await moveComponent.RotateWithAnimation(oldRotation, LevelDataConsts.NpcRecoverRotationDuration, TableCenter.global.Level_RotRestoreDelay.MillisecToSec());
                    moveComponent.EndSaveRotation();
                }
            }

        }

        public void HideTweenView()
        {
            foreach (var viewCom in _awaitViewList)
            {
                var moveCom = viewCom.entity.GetComponent<EntityMoveComponent>(ETComponentType.EntityMove);
                moveCom?.StopLookAtEntity();
                viewCom.HideAllAwaitView();
            }
            _awaitViewList.Clear();
        }

        protected override void OnDispose()
        {

        }
    }
}
